package org.xenon.vote.model.bo;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

import static org.xenon.vote.util.CharUtil.getRandomChar;

public class CaptchaFac {
    private static final int weight = 100;
    private static final int height = 40;
    private static final Random random = new Random();
    private static final int maxInterferingLine = 10;
    private static final int minFontSize = 24;
    private static final int fontSizeRange = 10;
    private static final String[] fontNames = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"};

    /**
     * 获取随机的颜色
     *
     */
    private static Color randomColor() {
        int r = random.nextInt(225);
        int g = random.nextInt(225);
        int b = random.nextInt(225);
        return new Color(r, g, b);
    }

    /**
     * 获取随机字体
     *
     */
    private static Font randomFont() {
        int index = random.nextInt(fontNames.length);
        String fontName = fontNames[index];
        int style = random.nextInt(4);
        int size = random.nextInt(fontSizeRange) + minFontSize;
        //noinspection MagicConstant
        return new Font(fontName, style, size);
    }


    /**
     * 马良
     */
    private static void drawLine(BufferedImage image) {
        int num = random.nextInt(maxInterferingLine);
        Graphics2D g = (Graphics2D) image.getGraphics();
        for (int i = 0; i < num; i++) {
            int x1 = random.nextInt(weight);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(weight);
            int y2 = random.nextInt(height);
            g.setColor(randomColor());
            g.drawLine(x1, y1, x2, y2);
        }
    }

    /**
     * 创建图片
     *
     */
    private static BufferedImage createImage() {
        BufferedImage image = new BufferedImage(weight, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = (Graphics2D) image.getGraphics();
        g.setColor(new Color(random.nextInt(245) + 10, random.nextInt(245) + 10, random.nextInt(245) + 10));
        g.fillRect(0, 0, weight, height);
        return image;
    }

    /**
     * 获取验证码的方法
     *
     */
    public static CaptchaImg getImage() {
        BufferedImage image = createImage();
        Graphics2D g = (Graphics2D) image.getGraphics();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            String s = getRandomChar() + "";
            sb.append(s);
            float x = i * 1.0F * weight / 4;
            g.setFont(randomFont());
            g.setColor(randomColor());
            g.drawString(s, x, height - 5);
        }
        drawLine(image);
        return new CaptchaImg(image, sb.toString());
    }
}